#!/usr/bin/env node

// 测试WeBASE连接的脚本
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');

// 读取input.json测试数据
const inputPath = path.join(__dirname, 'input.json');
let testData = null;

try {
  if (fs.existsSync(inputPath)) {
    testData = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
    console.log('📄 已读取input.json测试数据:', testData);
  } else {
    console.log('⚠️  input.json不存在，使用默认测试数据');
    testData = {
      preImage: "999999",
      dataHash: "21684337208779804888941250689604787706765813346243268687471433053195528470185"
    };
  }
} catch (error) {
  console.error('❌ 读取input.json失败:', error.message);
  testData = {
    preImage: "999999", 
    dataHash: "21684337208779804888941250689604787706765813346243268687471433053195528470185"
  };
}

// WeBASE配置 - 尝试多个配置
const WEBASE_CONFIGS = [
  {
    baseUrl: 'http://localhost:5002/WeBASE-Front',
    contractAddress: '0x1d38f5d0c8c1ae7ed63a2d0ec905b9e9a17e70cf',
    methodName: 'verifyAssetZKPacked',
    groupId: "group0", // 先试group0字符串格式
    user: '0x81fb4b53cb3aa863b23a23d560a2296b5752e87b'
  },
  {
    baseUrl: 'http://localhost:5002/WeBASE-Front',
    contractAddress: '0x1d38f5d0c8c1ae7ed63a2d0ec905b9e9a17e70cf',
    methodName: 'verifyAssetZKPacked',
    groupId: 0, // 数字格式
    user: '0x81fb4b53cb3aa863b23a23d560a2296b5752e87b'
  },
  {
    baseUrl: 'http://localhost:5002/WeBASE-Front',
    contractAddress: '0x1d38f5d0c8c1ae7ed63a2d0ec905b9e9a17e70cf',
    methodName: 'verifyAssetZKPacked',
    groupId: 1, // 原来的配置
    user: 'admin'
  }
];

// 模拟ABI编码（简化版本）
function encodeProofForTest(preImage, dataHash) {
  console.log('🔄 编码证明数据...');
  
  // 创建24个uint256元素的模拟数据
  const mockProofElements = [];
  const seed = parseInt(preImage) || 999999;
  
  // 生成18个G1点坐标（9个点 × 2坐标）
  for (let i = 0; i < 18; i++) {
    const value = (BigInt(seed) * BigInt(i + 1000) % BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617')).toString();
    const hexValue = BigInt(value).toString(16).padStart(64, '0');
    mockProofElements.push(hexValue);
  }
  
  // 生成6个评估标量
  for (let i = 0; i < 6; i++) {
    const value = (BigInt(seed) * BigInt(i + 2000) % BigInt('21888242871839275222246405745257275088548364400416034343698204186575808495617')).toString();
    const hexValue = BigInt(value).toString(16).padStart(64, '0');
    mockProofElements.push(hexValue);
  }
  
  // 添加dataHash
  const dataHashHex = BigInt(dataHash).toString(16).padStart(64, '0');
  mockProofElements.push(dataHashHex);
  
  const finalCalldata = '0x' + mockProofElements.join('');
  
  console.log('✅ 编码完成:');
  console.log('  - 证明元素数量:', 24);
  console.log('  - 数据哈希已包含:', true);
  console.log('  - 总大小:', finalCalldata.length / 2 - 1, '字节');
  console.log('  - Calldata前缀:', finalCalldata.slice(0, 100) + '...');
  
  return finalCalldata;
}

// 测试基础连接
async function testBasicConnection() {
  console.log('\n🔍 测试基础连接...');
  
  return new Promise((resolve) => {
    const req = http.get(WEBASE_CONFIGS[0].baseUrl, { timeout: 5000 }, (res) => {
      console.log(`✅ WeBASE服务响应: ${res.statusCode} ${res.statusMessage}`);
      res.on('data', (chunk) => {
        console.log('📥 响应数据:', chunk.toString().slice(0, 200) + '...');
      });
      res.on('end', () => {
        resolve(true);
      });
    });
    
    req.on('timeout', () => {
      console.log('⏰ 连接超时');
      req.destroy();
      resolve(false);
    });
    
    req.on('error', (error) => {
      console.log('❌ 连接错误:', error.message);
      resolve(false);
    });
  });
}

// 测试API端点 - 尝试多个配置
async function testApiEndpoint() {
  console.log('\n🎯 测试WeBASE API端点...');
  
  const packedProof = encodeProofForTest(testData.preImage, testData.dataHash);
  
  for (let i = 0; i < WEBASE_CONFIGS.length; i++) {
    const config = WEBASE_CONFIGS[i];
    console.log(`\n🔄 尝试配置 ${i + 1}/${WEBASE_CONFIGS.length}:`);
    console.log(`  - GroupId: ${config.groupId} (${typeof config.groupId})`);
    console.log(`  - User: ${config.user}`);
    
    const requestData = {
      groupId: config.groupId,
      user: config.user,
      contractAddress: config.contractAddress,
      funcName: config.methodName,
      funcParam: [packedProof],
      useCns: false
    };
    
    console.log('📤 发送请求到:', `${config.baseUrl}/trans/handle`);
    console.log('📋 请求数据:', JSON.stringify(requestData, null, 2));
    
    const postData = JSON.stringify(requestData);
    
    const options = {
      hostname: 'localhost',
      port: 5002,
      path: '/WeBASE-Front/trans/handle',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData),
        'Accept': 'application/json'
      },
      timeout: 10000
    };
    
    const success = await new Promise((resolve) => {
      const req = http.request(options, (res) => {
        console.log(`📥 API响应状态: ${res.statusCode} ${res.statusMessage}`);
        console.log('📋 响应头:', res.headers);
        
        let responseData = '';
        res.on('data', (chunk) => {
          responseData += chunk;
        });
        
        res.on('end', () => {
          console.log('📄 完整响应:', responseData);
          
          try {
            if (responseData) {
              const jsonResponse = JSON.parse(responseData);
              console.log('✅ 解析后的响应:', JSON.stringify(jsonResponse, null, 2));
              
              if (jsonResponse.code === 0) {
                console.log('🎉 区块链调用成功!');
                console.log('📊 交易结果:', jsonResponse.data);
                resolve(true);
                return;
              } else {
                console.log('⚠️  API返回错误:', jsonResponse.errorMessage || jsonResponse.message);
                
                // 检查是否是Group不存在的错误
                const errorMsg = jsonResponse.errorMessage || jsonResponse.message || '';
                if (errorMsg.includes('group not exist')) {
                  console.log('🔄 Group不存在，尝试下一个配置...');
                  resolve(false);
                  return;
                }
              }
            }
          } catch (error) {
            console.log('❌ 解析响应JSON失败:', error.message);
            console.log('原始响应:', responseData);
          }
          
          resolve(false);
        });
      });
      
      req.on('timeout', () => {
        console.log('⏰ API请求超时');
        req.destroy();
        resolve(false);
      });
      
      req.on('error', (error) => {
        console.log('❌ API请求错误:', error.message);
        resolve(false);
      });
      
      req.write(postData);
      req.end();
    });
    
    if (success) {
      console.log(`✅ 配置 ${i + 1} 成功!`);
      return true;
    }
  }
  
  console.log('❌ 所有配置都失败了');
  console.log('🔧 可能的解决方案:');
  console.log('  1. 检查WeBASE服务是否在localhost:5002运行');
  console.log('  2. 检查FISCO BCOS节点配置');
  console.log('  3. 确认Group配置是否正确');
  console.log('  4. 验证合约地址是否已部署');
  return false;
}

// 测试替代端口和URL
async function testAlternativeEndpoints() {
  console.log('\n🔄 测试替代端点...');
  
  const alternatives = [
    'http://localhost:5001/WeBASE-Front',
    'http://localhost:8080/WeBASE-Front', 
    'http://127.0.0.1:5002/WeBASE-Front',
    'http://localhost:5002/WeBASE-Front/1',
    'http://localhost:5002'
  ];
  
  for (const url of alternatives) {
    console.log(`🔍 尝试连接: ${url}`);
    
    await new Promise((resolve) => {
      const req = http.get(url, { timeout: 3000 }, (res) => {
        console.log(`  ✅ ${url} 响应: ${res.statusCode}`);
        res.on('data', () => {}); // consume data
        res.on('end', resolve);
      });
      
      req.on('timeout', () => {
        console.log(`  ⏰ ${url} 超时`);
        req.destroy();
        resolve();
      });
      
      req.on('error', () => {
        console.log(`  ❌ ${url} 无法连接`);
        resolve();
      });
    });
  }
}

// 主测试函数
async function runTests() {
  console.log('🚀 开始WeBASE连接测试...\n');
  
  console.log('📋 测试配置:');
  console.log('  - WeBASE URL:', WEBASE_CONFIGS[0].baseUrl);
  console.log('  - 合约地址:', WEBASE_CONFIGS[0].contractAddress);
  console.log('  - 调用方法:', WEBASE_CONFIGS[0].methodName);
  console.log('  - 配置数量:', WEBASE_CONFIGS.length);
  console.log('  - 测试数据:', testData);
  
  // 1. 基础连接测试
  const basicConnection = await testBasicConnection();
  
  // 2. API端点测试
  if (basicConnection) {
    await testApiEndpoint();
  } else {
    console.log('⚠️  基础连接失败，跳过API测试');
    await testAlternativeEndpoints();
  }
  
  console.log('\n📊 测试总结:');
  console.log('如果所有测试都失败，请检查:');
  console.log('1. WeBASE-Front服务是否正在运行');
  console.log('2. 服务端口是否为5002');
  console.log('3. 是否有防火墙阻止连接');
  console.log('4. 合约是否正确部署到区块链');
  
  console.log('\n✅ 测试完成!');
}

// 运行测试
runTests().catch(console.error);